import datetime
import os
import shutil
from urllib.parse import quote_plus

import pymysql
import requests
from sqlalchemy import create_engine
import pandas as pd

import logging
logging.basicConfig(
    level=logging.DEBUG,  # 设置日志级别
    format='%(asctime)s - %(levelname)s - %(message)s',  # 日志格式
    handlers=[
        logging.FileHandler('xhs_delete_user.log'),  # 将日志输出到文件
        logging.StreamHandler()  # 同时将日志输出到控制台
    ]
)

def delete_xhs_user(sql):
    con = pymysql.connect(host='rm-bp17r99475xuauk63yo.mysql.rds.aliyuncs.com', port=3306, user='live_data',
                          passwd='CJMg2tsHg7sj6bo0UTKq0a4T!fPDpJ', db='live_data', charset='utf8')
    # 获取操作数据的对象 cursor
    cursor = con.cursor()
    cursor.execute(sql)
    # sql_result = cursor.fetchall()
    # 提交事务
    con.commit()
    # 关闭Cursor
    cursor.close()
    # 关闭链接
    con.close()
    # time.sleep(2)
    return "删除成功"

"""删除用户chrome token"""


def delete_folder(chrome_id):
    try:
        shutil.rmtree(os.getcwd() + "\\user_info_dir\\" + chrome_id)
        print(f"成功删除文件夹")
    except OSError as e:
        print(f"删除文件夹失败")


"""查询xhs_account对应的spider_user_id账号"""


def pymysql_fetchall(sql):
    con = pymysql.connect(host='rm-bp17r99475xuauk63yo.mysql.rds.aliyuncs.com', port=3306, user='live_data',
                          passwd='CJMg2tsHg7sj6bo0UTKq0a4T!fPDpJ', db='live_data', charset='utf8')
    # 获取操作数据的对象 cursor
    cursor = con.cursor()
    cursor.execute(sql)
    sql_result = cursor.fetchall()
    # 提交事务
    con.commit()
    # 关闭Cursor
    cursor.close()
    # 关闭链接
    con.close()

    return sql_result

def mysql_config():
    user = 'live_data'
    password = quote_plus('CJMg2tsHg7sj6bo0UTKq0a4T!fPDpJ')
    # passwd ='merchantsasd123!@%&'
    host = 'rm-bp17r99475xuauk63yo.mysql.rds.aliyuncs.com'
    # port1 ='3306'
    dbname2 = 'live_data'
    engine2 = create_engine(f"mysql+pymysql://{user}:{password}@{host}:3306/{dbname2}?charset=utf8mb4")
    return engine2


def unbind_authorization_xhs_user(xhs_account):
    """删除用户chrome token"""
    chrome_sql = "select spider_user_id from live_data.xhs_user where xhs_account='{}'".format(xhs_account)
    chrome_sql_data = pymysql_fetchall(chrome_sql)



    xhs_user_info_sql = "delete from live_data.xhs_user_info where xhs_account='{}'".format(xhs_account)
    delete_xhs_user(xhs_user_info_sql)


    if chrome_sql_data == ():
        logging.debug(f"DELETE ERROR NO USER={xhs_account},code={'500'}")
        return {"msg":"删除操作失败，没有此用户","code":500}
    else:
        xhs_user_sql = "delete from live_data.xhs_user where xhs_account='{}'".format(xhs_account)
        delete_xhs_user(xhs_user_sql)
        logging.info(f"DELETE SUCCESS USER={xhs_account}")
        spider_user_id = chrome_sql_data[0][0]
        delete_folder(spider_user_id)

        """拿到spider_user_id 以后删除xhs_spider_config文件夹"""

        xhs_spider_config_sql = "delete from live_data.xhs_spider_config where spider_user_id='{}'".format(spider_user_id)
        delete_xhs_user(xhs_spider_config_sql)


        xhs_total_data_sql = "delete from live_data.xhs_total_data where xhs_account='{}'".format(xhs_account)
        delete_xhs_user(xhs_total_data_sql)

        xhs_account_data_sql = "delete from live_data.xhs_notes_account where xhs_account='{}'".format(xhs_account)
        delete_xhs_user(xhs_account_data_sql)

        xhs_notes_desc_data_sql = "delete from live_data.xhs_notes_desc where xhs_account='{}'".format(xhs_account)
        delete_xhs_user(xhs_notes_desc_data_sql)

        current_time = datetime.datetime.now()
        current_time = str(current_time)[:-7]
        log_json = {"xhs_account": xhs_account, "delete_time": current_time}
        delete_log_frame = pd.DataFrame([log_json])
        print(delete_log_frame)
        delete_log_frame["win"] = 'B'
        logging.info(f"CURRENT MACHINE={'B'},result={log_json}")
        pd.io.sql.to_sql(delete_log_frame, 'xhs_user_delete_log', mysql_config(), schema='live_data',
                         if_exists='append', index=False)
        return {"msg":"删除操作成功","code":200}
# unbind_authorization_xhs_user('5412188641')

